﻿#include "musicfolder.h"
#include "ui_musicfolder.h"
#include <QDebug>

MusicFolder::MusicFolder(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicFolder)
{
    ui->setupUi(this);

    player=nullptr;
    model=nullptr;
}

MusicFolder::~MusicFolder()
{
    if(player != nullptr)
    {
        player->close();
        player=nullptr;
    }
    delete ui;
}

void MusicFolder::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_F2:
        player->detectState();
        break;
    case Qt::Key_Escape:
        if(player->isPlaying())
            player->stop();
        else
            close();
        break;
    default:
        player->detectState();
        break;
    }
}

bool MusicFolder::initPlayer()
{
    player=new Player;
    if(!player->init())
    {
        player=nullptr;
        return false;
    }
    else
        return true;
}

void MusicFolder::initView()
{
    QString musicPath=QStandardPaths::writableLocation(QStandardPaths::MusicLocation);
    QStringList filter;
    filter << "*.ogg" << "*.mp3";

    model=new QFileSystemModel(this);
    model->setRootPath(musicPath);
    model->setNameFilters(filter);

    ui->treeView->setModel(model);
    ui->treeView->setRootIndex(model->index(musicPath));
    ui->treeView->hideColumn(1);
    ui->treeView->hideColumn(2);
    ui->treeView->hideColumn(3);
    ui->treeView->setHeaderHidden(true);

    ui->listView->setModel(model);
    ui->listView->setRootIndex(model->index(musicPath));

    connect(ui->treeView,SIGNAL(clicked(QModelIndex)),ui->listView,SLOT(setRootIndex(QModelIndex)));
    connect(ui->treeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(processMusicIndex(QModelIndex)));
    connect(ui->listView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(processMusicIndex(QModelIndex)));
}

void MusicFolder::processMusicIndex(const QModelIndex &index)
{
    if(model->isDir(index))
        return;

    QFileInfo file=model->fileInfo(index);
    QString fileName=file.absoluteFilePath();
    if(player->play(fileName))
        log(fileName);
    else
        QMessageBox::warning(this,"ERROR",QStringLiteral("音频文件无法播放！"));
}

void MusicFolder::log(const QString &fileName)
{
    QFile file(SONG_LIST);
    file.open(QFile::WriteOnly | QFile::Text |QFile::Append);
    QTextStream text(&file);
    text << fileName << "\n";
    file.close();
}
